package baoycode.view;

import java.util.HashSet;
import java.util.Set;

import org.eclipse.core.runtime.ILog;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.alibaba.druid.sql.SQLUtils;

import baoycode.Activator;
import baoycode.model.ColumnModel;
import baoycode.model.DataSourceBean;
import baoycode.model.TableModel;
import baoycode.utils.DBUtils;
import baoycode.utils.I18n;
import baoycode.utils.PathUtils;
import baoycode.utils.SerializeUtils;
import baoycode.utils.StringUtils;

public class SQLView extends TitleAreaDialog {
	
	static final ILog log = Activator.getDefault().getLog();

	public SQLView(Shell shell) {
		super(shell);
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		super.setMessage(I18n.sqlTitle, IMessageProvider.INFORMATION);
		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NULL);
		GridLayout layout = new GridLayout(3, false);
		layout.verticalSpacing = 10;
		container.setLayout(layout);

		connections = new List(container, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI);
		connections.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				if (connections.getSelectionIndex() == -1)
					return;
				if (connections.getSelectionIndex() == currentTableIndex)
					return;
				currentTableIndex = connections.getSelectionIndex();
				int i = 0;
				for (DataSourceBean d : dataSourceBeans) {
					if (i == connections.getSelectionIndex()) {
						selectedDataSource = d;
						break;
					}
					i++;
				}
				java.util.List<TableModel> tableModels = DBUtils.getTableList(selectedDataSource);
				for (TableModel tm : tableModels) {
					tables.add(tm.getName());
				}
			}
		});
		GridData connectionsStyle = new GridData(GridData.FILL_BOTH);
		connectionsStyle.heightHint = 400;
		connectionsStyle.widthHint = 100;
		connections.setLayoutData(connectionsStyle);

		Set<String> dsnames = new HashSet<String>();
		for (DataSourceBean ds : dataSourceBeans) {
			dsnames.add(ds.getDbName());
		}
		connections.setItems(dsnames.toArray(new String[dsnames.size()]));

		tables = new List(container, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI);
		tables.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				String tableName = tables.getItem(tables.getSelectionIndex());
				cms = DBUtils.getColumnList(selectedDataSource, tableName);
			}
		});
		GridData tablesStyle = new GridData(GridData.FILL_BOTH);
		tablesStyle.heightHint = 400;
		tablesStyle.widthHint = 150;
		tables.setLayoutData(tablesStyle);

		txtSql = new Text(container, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI);
		GridData txtSqlStyle = new GridData(GridData.FILL_BOTH);
		txtSqlStyle.heightHint = 400;
		txtSqlStyle.widthHint = 600;
		txtSql.setLayoutData(txtSqlStyle);
		return area;
	}

	@Override
	protected int getShellStyle() {
		return super.getShellStyle() | SWT.MIN | SWT.MAX | SWT.RESIZE;
	}

	/**
	 * 初始化对话框
	 */
	@Override
	@SuppressWarnings("unchecked")
	protected void configureShell(Shell newShell) {
		dataSourceBeans = (Set<DataSourceBean>) SerializeUtils.deserializeDecoder(PathUtils.getDataSourceFile());
		if (dataSourceBeans == null) {
			dataSourceBeans = new HashSet<DataSourceBean>();
		}
		super.configureShell(newShell);
	}

	/**
	 * OK 按钮单击后的回调方法
	 */
	@Override
	protected void okPressed() {
		MessageDialog.openInformation(null, "OK", I18n.saveSucc);
		// 执行保存
		super.okPressed();
	}

	/**
	 * cancel 按钮单击后的回调方法
	 */
	@Override
	protected void cancelPressed() {
		super.cancelPressed();
	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		// super.createButtonsForButtonBar(parent);
		// createButton(parent, IDialogConstants.CANCEL_ID, I18n.cancel, false);
	}

	protected Control createButtonBar(Composite parent) {
		Composite container = (Composite) super.createButtonBar(parent);
		Button btnFormat = createButton(container, 111, I18n.btnFormat, true);
		btnFormat.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String sql = txtSql.getText();
				if (StringUtils.isNotBlank(sql)) {
					String formatSql = SQLUtils.formatMySql(sql);
					txtSql.setText(formatSql);
				}
			}
		});
		createButton(container, 112, I18n.btnSelect, true).addSelectionListener(getBtnAdapter(I18n.SELECT));
		createButton(container, 113, I18n.btnInsert, true).addSelectionListener(getBtnAdapter(I18n.INSERT));
		createButton(container, 114, I18n.btnInsert, true).addSelectionListener(getBtnAdapter(I18n.INSERT_EXT));
		createButton(container, 115, I18n.btnUpdate, true).addSelectionListener(getBtnAdapter(I18n.UPDATE));
		createButton(container, 116, I18n.btnUpdate, true).addSelectionListener(getBtnAdapter(I18n.UPDATE_EXT));
		createButton(container, 117, I18n.cancel, true).addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				close();
			}
		});
		return container;
	}

	private SelectionAdapter getBtnAdapter(final int type) {
		return new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String tableName = tables.getItem(tables.getSelectionIndex());
				String sql = DBUtils.generateSQL(cms, tableName, type);
				txtSql.setText(sql);
			}
		};
	}

	List connections;
	List tables;
	Set<DataSourceBean> dataSourceBeans;
	DataSourceBean selectedDataSource;
	int currentTableIndex = -1;
	Text txtSql;
	java.util.List<ColumnModel> cms;
}
